package com.fsquare.controller.entity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javassist.expr.NewArray;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.openadmin.web.controller.entity.AdminBasicEntityController;
import org.broadleafcommerce.openadmin.web.form.entity.ComboField;
import org.broadleafcommerce.openadmin.web.form.entity.EntityForm;
import org.broadleafcommerce.openadmin.web.form.entity.Field;
import org.broadleafcommerce.openadmin.web.form.entity.FieldGroup;
import org.broadleafcommerce.openadmin.web.form.entity.Tab;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.fsquare.domain.invoice.Invoice;
import com.fsquare.service.invoice.InvoiceService;
import com.fsquare.service.invoice.type.TemplateType;


@Controller("fsquareAdminInvoiceController")
@RequestMapping("/" + AdminInvoiceController.SECTION_KEY)
public class AdminInvoiceController extends AdminBasicEntityController {
	protected static final Log LOG = LogFactory.getLog(AdminInvoiceController.class);
	protected static final String SECTION_KEY = "invoice";
	
	@Resource(name = "fsquareInvoiceService")
    protected InvoiceService invoiceService;
	
	@Override
    protected String getSectionKey(Map<String, String> pathVars) {
        if (super.getSectionKey(pathVars) != null) {
            return super.getSectionKey(pathVars);
        }
        return SECTION_KEY;
    }
	
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String viewEntityList(HttpServletRequest request, HttpServletResponse response, Model model,
            @PathVariable  Map<String, String> pathVars,
            @RequestParam  MultiValueMap<String, String> requestParams) throws Exception {
        String retString = super.viewEntityList(request, response, model, pathVars, requestParams);
        return retString;
    }
    
    @RequestMapping(value = "/{id}/uploadfile", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody Map<String, Object>  handleFileUpload(HttpServletRequest request, HttpServletResponse response, Model model, 
    		@RequestParam("file") MultipartFile file, @PathVariable(value="id") String id) {
    	
    	Map<String, Object> responseMap = new HashMap<String, Object>();
    	if ( !file.isEmpty() ) {
    		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)file;
    		String fileName = commonsMultipartFile.getFileItem().getName();
    		try {
    			Invoice invoice = invoiceService.readInvoiceById(Long.parseLong(id));
    			
    			invoice.setFileName(fileName);
    			invoice.setContentType(commonsMultipartFile.getFileItem().getContentType());
    			byte[] bytes = file.getBytes();
    			
    			invoice.setFile(bytes);
    			invoiceService.saveInvoice(invoice);

    			Map<String, String> filemap = new HashMap<String, String>();
    			filemap.put("deleteType", "DELETE");
    			filemap.put("deleteUrl", "");
    			filemap.put("name", fileName);
    			filemap.put("size", ""+commonsMultipartFile.getSize());
    			filemap.put("thumbnailUrl", "");
    			filemap.put("type", "");
    			filemap.put("url", "");
    			responseMap.put("files", new Object[] {filemap});

                return responseMap;
    		}catch ( Exception e ) {
    			LOG.error(e, e);
    			return responseMap;
    		}
    	} else {
    		return responseMap;
    	}
    }
    
    @RequestMapping(value = "/{id}/downloadfile", method = RequestMethod.GET, produces = "application/json")
    public void  handleFileDownload(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable(value="id") String id) {
  
    	try {
	    	Invoice invoice = invoiceService.readInvoiceById(Long.parseLong(id));
	    	String fileName = invoice.getFileName();
//	    	System.out.println("fileName: "+fileName);
	    	response.setContentType(invoice.getContentType());	    	
	    	response.setHeader("Content-Disposition","attachment; filename=\"_" + fileName +"\"");
	    	OutputStream outStream = response.getOutputStream();
//	    	outStream.write(invoice.getFile());
//	    	response.setProperty("Content-Disposition", "attachment; filename="+ fileName);
	    	
	    	
//	    	response.setContentType(file.getType());
//	        response.setContentLength(file.getFile().length);
	        
	    	invoiceService.getOrderInvoice(Long.parseLong(id), outStream);

    		outStream.close();
	    }catch(Exception e){
	        e.printStackTrace();
	    }

    }
    
    
    @Override
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String viewEntityForm(HttpServletRequest request, HttpServletResponse response, Model model,
            @PathVariable  Map<String, String> pathVars,
            @PathVariable(value="id") String id) throws Exception {
        
    	String view = super.viewEntityForm(request, response, model, pathVars, id);
        
    	EntityForm entityForm = (EntityForm) model.asMap().get("entityForm");
    	ComboField templateTypeField = (ComboField)entityForm.findField("templateType");
    	
    	for(TemplateType opt: TemplateType.values()) {
    		templateTypeField.putOption(opt.toString(), opt.toString());
    	}
    	
//    	templateTypeField.se
//    	Field newField = new Field();
//    	newField.setFieldType("filedownload");
//		newField.setReadOnly(true);
//		newField.setValue(entityForm.);
//    	entityForm.findTabForField(fieldName)
//    	Field field = entityForm.findField("fileName");
//    	field.setFieldType("filedownload");
//
//    	
//    	entityForm = (EntityForm) model.asMap().get("entityForm");
//    	field = entityForm.findField("fileName");
//    	
        return view;
    }
    
    
}
